<template>
  <div class="task-list">
    <div class="page-header">
      <h2>{{ $t('tasks.title') }}</h2>
      <a-button type="primary" @click="showTaskForm()">
        <PlusOutlined />
        {{ $t('tasks.create') }}
      </a-button>
    </div>

    <!-- New Filter Container -->
    <div class="filter-container">
      <div class="filter-header" @click="toggleFilters" role="button" tabindex="0">
        <h3>{{ $t('common.search') }}</h3>
        <a-button type="text" class="filter-toggle-button">
          {{ filtersVisible ? $t('common.close') : $t('common.search') }}
          <template #icon>
            <UpOutlined v-if="filtersVisible" />
            <DownOutlined v-else />
          </template>
        </a-button>
      </div>

      <transition name="slide-fade">
        <div v-show="filtersVisible" class="filter-bar-content">
          <!-- Original filter-bar div now acts as content wrapper -->
          <div class="filter-item">
            <div class="filter-label">{{ $t('tasks.columns.name') }}</div>
            <a-input
              v-model:value="searchText"
              :placeholder="$t('tasks.form.nameRequired')"
              allow-clear
            >
              <template #prefix>
                <SearchOutlined />
              </template>
            </a-input>
          </div>
          
          <div class="filter-item">
            <div class="filter-label">{{ $t('tasks.columns.status') }}</div>
            <a-select
              v-model:value="statusFilter"
              :placeholder="$t('tasks.columns.status')"
              style="width: 100%"
              allow-clear
            >
              <a-select-option value="enabled">{{ $t('tasks.status.enabled') }}</a-select-option>
              <a-select-option value="disabled">{{ $t('tasks.status.disabled') }}</a-select-option>
              <a-select-option value="running">{{ $t('tasks.status.running') }}</a-select-option>
              <a-select-option value="stopped">{{ $t('logs.status.stopped') }}</a-select-option>
            </a-select>
          </div>
          
          <div class="filter-item">
            <div class="filter-label">{{ $t('tasks.columns.createdAt') }}</div>
            <a-range-picker
              v-model:value="createTimeRange"
              :placeholder="[$t('common.search'), $t('common.search')]"
              style="width: 100%"
              :show-time="{ format: 'HH:mm' }"
              format="YYYY-MM-DD HH:mm"
              allow-clear
            />
          </div>
          
          <div class="filter-item">
            <div class="filter-label">{{ $t('common.update') }}</div>
            <a-range-picker
              v-model:value="updateTimeRange"
              :placeholder="[$t('common.search'), $t('common.search')]"
              style="width: 100%"
              :show-time="{ format: 'HH:mm' }"
              format="YYYY-MM-DD HH:mm"
              allow-clear
            />
          </div>
        </div>
      </transition>
    </div>

    <a-table
      :columns="columns"
      :data-source="filteredTasks"
      :loading="loading"
      row-key="id"
      :pagination="{ pageSize: 10 }"
      :scroll="{ x: 1400 }"
      :row-class-name="(record: Task, _index: number) => (record.isPinned ? 'pinned-task-row' : null)"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'name'">
          <span style="display: inline-flex; align-items: center;">
            <a-tag v-if="record.isPinned" color="gold" style="margin-right: 8px; line-height: normal; padding: 0 4px;">
              <template #icon><PushpinFilled /></template>
              {{ $t('tasks.actions.pin') }}
            </a-tag>
            {{ record.name }}
          </span>
        </template>
        <template v-else-if="column.key === 'command'">
          <a @click="showFullCommand(record.command)" class="command-link" :title="record.command">
            {{ record.command }}
          </a>
        </template>
        <template v-else-if="column.key === 'schedule'">
          <a-tooltip>
            <template #title>{{ record.schedule }}</template>
            <span>{{ parseCronToHumanReadable(record.schedule) }}</span>
          </a-tooltip>
        </template>
        <template v-else-if="column.key === 'taskStatus'">
          <!-- 显示启用/禁用状态 -->
          <template v-if="record.enabled">
            <a-tag color="success">
              {{ $t('tasks.status.enabled') }}
            </a-tag>
          </template>
          <template v-else>
            <a-tag color="default">
              {{ $t('tasks.status.disabled') }}
            </a-tag>
          </template>
        </template>
        <template v-else-if="column.key === 'runningStatus'">
          <!-- 显示运行状态 -->
          <template v-if="record.running">
            <a-tag color="processing" style="cursor: pointer" @click="viewOutput(record)">
              <span style="display: flex; align-items: center; gap: 4px;">
                {{ $t('tasks.status.running') }}
              </span>
            </a-tag>
          </template>
          <template v-else>
            <a-tag color="default">
              {{ $t('logs.status.stopped') }}
            </a-tag>
          </template>
        </template>
        <template v-else-if="column.key === 'nextRun'">
          <span v-if="record.enabled && record.nextRun && record.nextRun !== '0001-01-01T00:00:00Z' && record.nextRun !== '' && new Date(record.nextRun).getTime() > 0">
            {{ formatTime(record.nextRun) }}
          </span>
          <span v-else-if="record.enabled" class="text-muted">{{ $t('common.loading') }}</span>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'lastRun'">
          <span v-if="record.lastRun">
            {{ formatTime(record.lastRun) }}
          </span>
          <span v-else class="text-muted">{{ $t('logs.messages.noOutput') }}</span>
        </template>
        <template v-else-if="column.key === 'createdAt'">
          <span v-if="record.createdAt">
            {{ formatTime(record.createdAt) }}
          </span>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'updatedAt'">
          <span v-if="record.updatedAt">
            {{ formatTime(record.updatedAt) }}
          </span>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'actions'">
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              <MoreOutlined style="font-size: 16px" />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item
                  key="toggle-pin"
                  @click="handleTogglePin(record)"
                >
                  <template #icon><PushpinOutlined /></template>
                  {{ record.isPinned ? $t('tasks.actions.unpin') : $t('tasks.actions.pin') }}
                </a-menu-item>
                <a-menu-divider v-if="record.isPinned" />
                <a-menu-item 
                  key="edit" 
                  @click="showTaskForm(record)"
                  :disabled="record.running"
                >
                  <template #icon><EditOutlined /></template>
                  {{ $t('tasks.actions.edit') }}
                </a-menu-item>
                <a-menu-item 
                  key="execute" 
                  @click="executeTask(record)"
                  :disabled="record.running"
                >
                  <template #icon><PlayCircleOutlined /></template>
                  {{ $t('tasks.actions.execute') }}
                </a-menu-item>
                <a-menu-item 
                  key="toggle" 
                  @click="toggleTask(record)"
                  :disabled="record.running"
                >
                  <template #icon>
                    <PoweroffOutlined v-if="record.enabled" />
                    <PlaySquareOutlined v-else />
                  </template>
                  {{ record.enabled ? $t('tasks.actions.disable') : $t('tasks.actions.enable') }}
                </a-menu-item>
                <a-menu-item 
                  key="stop" 
                  @click="stopTask(record)"
                  v-if="record.running"
                  danger
                >
                  <template #icon><StopOutlined /></template>
                  {{ $t('tasks.actions.stop') }}
                </a-menu-item>
                <a-menu-item 
                  key="output" 
                  @click="viewOutput(record)"
                  v-if="record.running"
                >
                  <template #icon><EyeOutlined /></template>
                  {{ $t('tasks.actions.viewOutput') }}
                </a-menu-item>
                <a-menu-item key="logs" @click="viewLogs(record)">
                  <template #icon><FileTextOutlined /></template>
                  {{ $t('tasks.actions.viewLogs') }}
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item key="delete" @click="deleteTask(record)" danger>
                  <template #icon><DeleteOutlined /></template>
                  {{ $t('tasks.actions.delete') }}
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </template>
    </a-table>

    <!-- 任务表单模态窗口 -->
    <TaskFormModal
      :open="taskFormVisible"
      :task="currentTask"
      @update:open="taskFormVisible = $event"
      @success="handleTaskSuccess"
    />

    <!-- 任务日志模态窗口 -->
    <TaskLogModal
      :open="logModalVisible"
      :task-id="currentTask?.id"
      :execution-id="currentExecutionId"
      @update:open="logModalVisible = $event"
    />

    <a-modal
      v-model:open="fullCommandModalVisible"
      title="完整执行命令"
      :footer="null"
      :width="600"
    >
      <div class="full-command-content">
        <pre>{{ currentFullCommand }}</pre>
      </div>
      <template #footer>
        <a-button key="close" @click="fullCommandModalVisible = false">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { message, Modal } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs'
import {
  PlusOutlined,
  SearchOutlined,
  EditOutlined,
  FileTextOutlined,
  DeleteOutlined,
  PlayCircleOutlined,
  MoreOutlined,
  EyeOutlined,
  StopOutlined,
  PoweroffOutlined,
  PlaySquareOutlined,
  PushpinOutlined,
  UpOutlined,
  DownOutlined,
  PushpinFilled
} from '@ant-design/icons-vue'
import { parseCronToHumanReadable } from '@/utils/cronParser'
import TaskFormModal from '@/components/TaskFormModal.vue'
import TaskLogModal from '@/components/TaskLogModal.vue'
import { taskAPI } from '@/api'
import type { Task } from '@/types/task'

const { t } = useI18n()
const router = useRouter()

const loading = ref(false)
const searchText = ref('')
const statusFilter = ref<string>()
const tasks = ref<Task[]>([])
const taskFormVisible = ref(false)
const logModalVisible = ref(false)
const currentTask = ref<Task>()
const currentExecutionId = ref<string>()
const createTimeRange = ref<[Dayjs | null, Dayjs | null] | null>(null)
const updateTimeRange = ref<[Dayjs | null, Dayjs | null] | null>(null)
const filtersVisible = ref(false)
const fullCommandModalVisible = ref(false)
const currentFullCommand = ref('')

const columns = computed(() => [
  {
    title: t('tasks.columns.name'),
    dataIndex: 'name',
    key: 'name',
    width: '12%'
  },
  {
    title: t('tasks.columns.command'),
    dataIndex: 'command',
    key: 'command',
    width: '18%'
  },
  {
    title: t('tasks.columns.schedule'),
    dataIndex: 'schedule',
    key: 'schedule',
    width: '10%'
  },
  {
    title: t('tasks.columns.status'),
    key: 'taskStatus',
    width: 100,
    align: 'center'
  },
  {
    title: t('logs.columns.status'),
    key: 'runningStatus',
    width: 100,
    align: 'center'
  },
  {
    title: t('tasks.columns.nextRun'),
    key: 'nextRun',
    width: 180
  },
  {
    title: t('logs.columns.endTime'),
    key: 'lastRun',
    width: 180
  },
  {
    title: t('tasks.columns.createdAt'),
    key: 'createdAt',
    width: 180,
    sorter: (a: Task, b: Task) => {
      const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0
      const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0
      return timeA - timeB
    }
  },
  {
    title: t('common.update'),
    key: 'updatedAt',
    width: 180,
    sorter: (a: Task, b: Task) => {
      const timeA = a.updatedAt ? new Date(a.updatedAt).getTime() : 0
      const timeB = b.updatedAt ? new Date(b.updatedAt).getTime() : 0
      return timeA - timeB
    }
  },
  {
    title: t('tasks.columns.actions'),
    key: 'actions',
    fixed: 'right',
    width: 100,
    align: 'center'
  }
])

const filteredTasks = computed(() => {
  let filtered = tasks.value

  if (searchText.value) {
    filtered = filtered.filter(task =>
      task.name.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }

  if (statusFilter.value !== undefined) {
    if (statusFilter.value === 'enabled') {
      filtered = filtered.filter(task => task.enabled && !task.running)
    } else if (statusFilter.value === 'disabled') {
      filtered = filtered.filter(task => !task.enabled && !task.running)
    } else if (statusFilter.value === 'running') {
      filtered = filtered.filter(task => task.running)
    } else if (statusFilter.value === 'stopped') {
      filtered = filtered.filter(task => !task.running)
    }
  }

  if (createTimeRange.value && createTimeRange.value.length === 2) {
    const [startTime, endTime] = createTimeRange.value
    if (startTime && endTime) {
      filtered = filtered.filter(task => {
        const taskTime = task.createdAt ? new Date(task.createdAt).getTime() : 0
        return taskTime >= startTime.valueOf() && taskTime <= endTime.valueOf()
      })
    }
  }

  if (updateTimeRange.value && updateTimeRange.value.length === 2) {
    const [startTime, endTime] = updateTimeRange.value
    if (startTime && endTime) {
      filtered = filtered.filter(task => {
        const taskTime = task.updatedAt ? new Date(task.updatedAt).getTime() : 0
        return taskTime >= startTime.valueOf() && taskTime <= endTime.valueOf()
      })
    }
  }

  return filtered
})

const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const showTaskForm = (task?: Task) => {
  currentTask.value = task
  taskFormVisible.value = true
}

const handleTaskSuccess = (task: Task) => {
  if (currentTask.value) {
    // 编辑任务 - 刷新列表以获取最新的nextRun等字段
    loadTasks()
  } else {
    // 新建任务
    tasks.value.unshift(task)
    // 刷新任务列表以获取最新状态（可能包括立即执行的状态）
    setTimeout(() => {
      loadTasks()
    }, 500) // 延迟500ms刷新，确保后端状态已更新
  }
}

const viewLogs = (task: Task) => {
  router.push(`/logs?taskId=${task.id}`)
}

const viewOutput = (task: Task) => {
  console.log('[TaskList] viewOutput: 任务信息:', {
    taskId: task.id,
    taskName: task.name,
    running: task.running,
    executionId: task.executionId
  })
  
  if (task.executionId && task.executionId.trim() !== '') {
    currentTask.value = task
    currentExecutionId.value = task.executionId
    logModalVisible.value = true
    console.log('[TaskList] viewOutput: 打开日志弹窗，executionId:', task.executionId)
  } else {
    console.log('[TaskList] viewOutput: 任务没有有效的executionId，task:', task)
    message.warning(t('common.warning'))
  }
}

const executeTask = async (task: Task) => {
  // 如果前端状态显示任务正在运行，直接提示并打开日志窗口
  if (task.running) {
    message.info(t('tasks.messages.executeSuccess'))
    viewOutput(task)
    return
  }

  try {
    console.log('[TaskList] executeTask: 开始执行任务:', { taskId: task.id, taskName: task.name })
    const data = await taskAPI.executeTask(task.id)
    console.log('[TaskList] executeTask: 执行任务API响应:', data)
    
    if (data.success) {
      message.success(t('tasks.messages.executeSuccess'))
      // 更新任务状态
      task.running = true
      task.executionId = data.executionId
      console.log('[TaskList] executeTask: 设置executionId:', data.executionId)
      
      // 显示日志窗口
      currentTask.value = task
      currentExecutionId.value = data.executionId
      logModalVisible.value = true
      console.log('[TaskList] executeTask: 打开日志弹窗，executionId:', data.executionId)
      
      // 刷新任务列表
      loadTasks()
    } else {
      message.error(data.message || t('common.error'))
    }
  } catch (error: any) {
    console.error('[TaskList] executeTask: 执行任务失败:', error)
    
    const errorMsg = error.response?.data?.msg || error.message || ''
    
    // 特殊处理"任务已在运行"的错误
    if (errorMsg.includes('already running') || errorMsg.includes('is already running') || errorMsg.includes('正在运行中')) {
      // 尝试从错误消息中提取executionId
      const executionIdMatch = errorMsg.match(/executionId:\s*([a-f0-9-]+)/i)
      const extractedExecutionId = executionIdMatch ? executionIdMatch[1] : null
      
      // 刷新任务列表以获取最新状态
      await loadTasks()
      
      // 查找更新后的任务
      const updatedTask = tasks.value.find(t => t.id === task.id)
      if (updatedTask?.running && (updatedTask.executionId || extractedExecutionId)) {
        // 如果任务确实在运行且有executionId，直接打开日志窗口
        currentTask.value = updatedTask
        currentExecutionId.value = updatedTask.executionId || extractedExecutionId
        logModalVisible.value = true
        message.success(t('tasks.messages.executeSuccess'))
      } else {
        // 状态不一致，给出提示
        message.warning(t('common.loading'))
      }
      return
    }
    
    // 如果是任务不存在的错误，刷新任务列表
    if (errorMsg.includes('task not found')) {
      message.error(t('common.error'))
      loadTasks()
    } else {
      message.error(errorMsg || t('common.error'))
    }
  }
}

const stopTask = async (task: Task) => {
  Modal.confirm({
    title: t('tasks.actions.stop'),
    content: t('tasks.messages.deleteConfirm', { name: task.name }),
    okText: t('tasks.actions.stop'),
    okType: 'danger',
    cancelText: t('common.cancel'),
    maskClosable: false,
    width: 480,
    onOk: async () => {
      try {
        const data = await taskAPI.stopTask(task.id)
        if (data.success) {
          message.success(t('tasks.messages.stopSuccess'))
          // 更新任务状态
          task.running = false
          task.executionId = undefined
          // 刷新任务列表
          loadTasks()
        } else {
          message.error(data.message ? data.message : t('common.error'))
        }
      } catch (error) {
        message.error(t('common.error'))
      }
    }
  })
}

const toggleTask = async (task: Task) => {
  const action = task.enabled ? t('tasks.actions.disable') : t('tasks.actions.enable')
  
  Modal.confirm({
    title: t('common.confirm'),
    content: t('tasks.messages.deleteConfirm', { name: task.name }),
    okText: action,
    okType: task.enabled ? 'danger' : 'primary',
    cancelText: t('common.cancel'),
    maskClosable: false,
    width: 480,
    onOk: async () => {
      try {
        const updatedTask = await taskAPI.toggleTask(task.id)
        message.success(t('tasks.messages.toggleSuccess'))
        // 更新任务状态
        task.enabled = updatedTask.enabled
        task.nextRun = updatedTask.nextRun
        // 刷新任务列表
        loadTasks()
      } catch (error: any) {
        message.error(error.response?.data?.msg || t('common.error'))
      }
    }
  })
}

const deleteTask = (task: Task) => {
  Modal.confirm({
    title: t('common.confirm'),
    content: t('tasks.messages.deleteConfirm', { name: task.name }),
    okText: t('tasks.actions.delete'),
    okType: 'danger',
    cancelText: t('common.cancel'),
    maskClosable: false,
    onOk: async () => {
      try {
        await taskAPI.deleteTask(task.id)
        tasks.value = tasks.value.filter(t => t.id !== task.id)
        message.success(t('tasks.messages.deleteSuccess'))
      } catch (error) {
        message.error(t('common.error'))
      }
    }
  })
}

const handleTogglePin = async (task: Task) => {
  try {
    await taskAPI.togglePinTask(task.id)
    message.success(task.isPinned ? t('tasks.messages.unpinSuccess') : t('tasks.messages.pinSuccess'))
    loadTasks() // 重新加载列表以查看排序和状态变化
  } catch (error) {
    message.error(t('common.error'))
    console.error('Failed to toggle pin status:', error)
  }
}

const showFullCommand = (command: string) => {
  currentFullCommand.value = command
  fullCommandModalVisible.value = true
}

const loadTasks = async () => {
  loading.value = true
  try {
    console.log('正在加载任务列表...')
    const result = await taskAPI.getTasks()
    // 确保result是数组，如果不是则使用空数组
    tasks.value = Array.isArray(result) ? result : []
    console.log('任务列表加载成功:', tasks.value.length, '个任务')
    if (tasks.value.length > 0) {
      console.log('任务ID列表:', tasks.value.map(t => ({ id: t.id, name: t.name })))
    }
  } catch (error: any) {
    console.error('加载任务列表失败:', error)
    message.error(error.response?.data?.msg || t('common.error'))
    tasks.value = []
  } finally {
    loading.value = false
  }
}

const toggleFilters = () => {
  filtersVisible.value = !filtersVisible.value
}

onMounted(() => {
  loadTasks()
})
</script>

<style lang="less" scoped>
.task-list {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.filter-container {
  margin-bottom: 24px;
  border-bottom: 1px solid #e8e8e8;
  border-radius: 6px;
  background-color: #fff;
  overflow: hidden;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.filter-header:hover {
  background-color: #f9f9f9;
}

.filter-header h3 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
}

.filter-toggle-button.ant-btn-text {
  padding: 0 4px;
  color: #555;
}

.filter-toggle-button.ant-btn-text:hover,
.filter-toggle-button.ant-btn-text:focus {
  color: #1890ff;
  background-color: transparent;
}

.filter-bar-content {
  padding: 16px;
  padding-top: 0;
  max-width: 520px;
  margin: 0 auto;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.filter-item:last-child {
  margin-bottom: 0;
}

.filter-label {
  margin-bottom: 0;
  margin-right: 12px;
  font-weight: 600;
  font-size: 14px;
  color: #333;
  flex-shrink: 0;
  width: 100px;
  text-align: right;
}

.filter-item > :deep(.ant-select),
.filter-item > :deep(.ant-picker),
.filter-item > :deep(.ant-input-affix-wrapper) {
  flex-grow: 1;
  width: auto;
}

.text-muted {
  color: #999;
}

.ant-dropdown-link {
  color: #1890ff;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.ant-dropdown-link:hover {
  background-color: rgba(24, 144, 255, 0.1);
}

:deep(.ant-dropdown-menu-item) {
  min-width: 120px;
  padding: 10px 16px !important;
}

:deep(.ant-dropdown-menu-item .anticon) {
  font-size: 14px;
  margin-right: 12px;
}

:deep(.ant-dropdown-menu) {
  padding: 4px;
}

:deep(.ant-dropdown-menu-item:not(:last-child)) {
  margin-bottom: 2px;
}

:deep(.ant-dropdown-menu-item:hover) {
  background-color: rgba(24, 144, 255, 0.06);
}

:deep(.ant-dropdown-menu-item-danger) {
  color: #ff4d4f !important;
}

:deep(.ant-dropdown-menu-item-danger:hover) {
  background-color: rgba(255, 77, 79, 0.06) !important;
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease-in-out;
  max-height: 500px;
  overflow: hidden;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
}

.slide-fade-enter-to,
.slide-fade-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 500px;
}

.command-link {
  cursor: pointer;
  color: #1890ff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  max-width: 100%;
  vertical-align: bottom;
}

.command-link:hover {
  text-decoration: underline;
}

.full-command-content pre {
  // ... existing code ...
}
</style> 